﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NCRGEA.AAL;
using System.IO;

using System.Data.SqlClient;

namespace NCRGEA.Admin
{
    public partial class frmExportDeductions : Form
    {
        public frmExportDeductions()
        {
            Logger.Log("Export Deductions screen loaded.");
            InitializeComponent();

            loadData();

            updateGrid();
        }

        #region Global Variables
        
        /// <summary>
        /// This stores all the members that are Active, Updated or Deleted status
        /// </summary>
        DataTable myData = new DataTable();

        #endregion

        #region Data Manipulation

        /// <summary>
        /// Load all the necessary data
        /// </summary>
        private void loadData()
        {
            Logger.Log("Begining Data Loading");

            string query = @"SELECT
                                mi.MemberID, mi.DedFlag, mi.FirstName,  mi.LastName, mi.Sex, mi.DOB, mi.City, mi.State, mi.SSN,
                                md.Amount
                            FROM
                                memInfo mi
                                    INNER JOIN
                                        memDues md
                                    ON
                                        mi.DuesID = md.DuesID
                            WHERE
                                mi.DedFlag = 'A' OR mi.DedFlag = 'D' OR mi.DedFlag = 'U'";

            myData = DAL.ExecuteQuery(query);

            Logger.Log("Data loaded into Data Table myData.");
        }

        #endregion

        #region Control Manipulation

        private void exportDeductions()
        {

        }

        /// <summary>
        /// Updates the grid for the user
        /// </summary>
        private void updateGrid()
        {
            Logger.Log("Begining data display.");

            grdExport.DataSource = myData;

            foreach (DataGridViewColumn a in grdExport.Columns)
                a.ReadOnly = true;

            grdExport.Columns[0].ReadOnly = false;

            Logger.Log("Datagrid loaded.");
        }

        #endregion

        private void btnSelectAll_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow d in grdExport.Rows)
                d.Cells[0].Value = 1;
        }

        private void btnSelectNone_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow d in grdExport.Rows)
                d.Cells[0].Value = 0;
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            Logger.Log("Loading update statements and begining file output.");

            List<int> memberIDs = new List<int>();
            List<string> formattedTotal = new List<string>();

            string tempFormat = string.Empty;

            foreach (DataGridViewRow d in grdExport.Rows)
            {
                if (d.Cells[0].Value != null)
                    if (d.Cells[0].Value.ToString() == "1")
                    {
                        tempFormat = d.Cells["DedFlag"].Value.ToString();
                        tempFormat += d.Cells["SSN"].Value.ToString();
                        //tempFormat += d.Cells["Amount"].Value.ToString();

                        string sTemp = d.Cells["Amount"].Value.ToString();
                        double dTemp = double.Parse(sTemp);
                        tempFormat += string.Format("{0:0000.00}", dTemp);

                        sTemp = d.Cells["MemberID"].Value.ToString();
                        int iTemp = int.Parse(sTemp);

                        memberIDs.Add(iTemp);
                        formattedTotal.Add(tempFormat);

                        Logger.Log("MemberID: " + iTemp);
                        Logger.Log("Formatted String: " + tempFormat);
                    }
            }

            exportData(formattedTotal);
            updateDataBase(memberIDs);
        }

        /// <summary>
        /// Sets all the user's DedFlag to zero
        /// </summary>
        /// <param name="list"></param>
        private void updateDataBase(List<int> list)
        {
            Logger.Log("Begining DataBaseUpdate");

            string pQuery = @"UPDATE
                                memInfo mi
                              SET
                                mi.Dedflag = ''
                             WHERE
                                mi.MemberID = @memberID";

            SqlParameter[] param = new SqlParameter[1];

            foreach (int a in list)
            {
                param[0] = new SqlParameter("@memberID", a);

                Logger.Log("Executing Query of: " + pQuery);

                DAL.ExecuteNonQuery(pQuery, param);
            }

            Logger.Log("All queries completed sucessfully.");
        }

        /// <summary>
        /// Write the data to a textbox.
        /// TODO: Write to an FTP server
        /// </summary>
        /// <returns>Returns true if the file was written to sucessfully. False if it was unable to write to the file</returns>
        private bool exportData(List<string> dataList)
        {
            string beginingFileName = "DED200";

            DateTime date = DateTime.Now;

            beginingFileName += string.Format("{0:00}", date.Month) + ".txt";

            const string location = "D:\\Documents and Settings\\Scott\\Desktop\\NCRGEA\\trunk\\Files\\";
            Logger.Log("Begining Exporting Script.");

            if (!(File.Exists(location + beginingFileName)))
            {
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(location + beginingFileName))
                {
                    foreach (string a in dataList)
                    {
                        file.WriteLine(a);
                    }
                }
            }
            else
            {
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(location + beginingFileName,true))
                {
                    foreach (string a in dataList)
                    {
                        file.WriteLine(a);
                    }
                }
            }

            return true;
        }
    }
}
